<template>
  <el-dialog title="分配菜单" :visible.sync="visible">
    <el-tree :data="menuTreeList" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current
      :props="defaultProps">
    </el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSave()" size="small">确定</el-button>
      <el-button @click="handleClear()" size="small">重置</el-button>
      <el-button @click="visible = false" size="small">取 消</el-button> 
    </span>
  </el-dialog>
</template>

<script>
import { fetchTreeList } from '@/api/sys/menu';
import { listMenuByRole, allocMenu } from '@/api/sys/role';

export default {
  name: "allocMenu",
  data() {
    return {
      visible: false,
      menuTreeList: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      roleId: null
    };
  },
  methods: {
    init(id) {
      this.roleId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.treeList();
        if (this.roleId) {
          this.getRoleMenu(this.roleId);
        }
      })
    },
    treeList() {
      fetchTreeList().then(response => {
        this.menuTreeList = response.data;
      });
    },
    getRoleMenu(roleId) {
      listMenuByRole(roleId).then(response => {
        let menuList = response.data;
        let checkedMenuIds = [];
        if (menuList != null && menuList.length > 0) {
          for (let i = 0; i < menuList.length; i++) {
            let menu = menuList[i];
            if (menu.parentId !== 0) {
              checkedMenuIds.push(menu.id);
            }
          }
        }
        this.$refs.tree.setCheckedKeys(checkedMenuIds);
      });
    },
    handleSave() {
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      let checkedMenuIds = new Set();
      if (checkedNodes != null && checkedNodes.length > 0) {
        for (let i = 0; i < checkedNodes.length; i++) {
          let checkedNode = checkedNodes[i];
          checkedMenuIds.add(checkedNode.id);
          if (checkedNode.parentId !== 0) {
            checkedMenuIds.add(checkedNode.parentId);
          }
        }
      }
      let params = new URLSearchParams();
      params.append("roleId", this.roleId);
      params.append("menuIds", Array.from(checkedMenuIds));
      allocMenu(params).then(response => {
        this.$message({
          message: '分配成功',
          type: 'success',
          duration: 1000
        });
        this.visible = false;
        this.$emit('refreshDataList');
      })
    },
    handleClear() {
      this.$refs.tree.setCheckedKeys([]);
    }
  }
}
</script>

<style scoped></style>
